package com.geh.learn.thread.completablefuture;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

public class OtherExample {

    static void allOfTest() throws ExecutionException, InterruptedException {
        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {waite(10); return "Hello";});
        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {waite(5); return "Beautiful";});
        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {waite(1); return "World";});

        List<CompletableFuture> futures = Lists.newArrayList(future1, future2, future3);

        StringBuilder result = new StringBuilder();

        CompletableFuture<Void> allCompleteFeature = CompletableFuture.allOf(future1, future2, future3)
                .whenComplete((aVoid, throwable) -> {
                    futures.forEach(f -> result.append(f.getNow(null)));
                    result.append("done");
                });

        allCompleteFeature.join();

        System.out.println(result);
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {

        long start = System.currentTimeMillis();

        allOfTest();

        System.out.println((System.currentTimeMillis() - start) / 1000);

    }

    static void waite(int seconds) {
        try {
            TimeUnit.SECONDS.sleep(seconds);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
